"""
Define a Python xts class equivalent to the R xts class.  
Drop the class idea until found necessary.

An xts object is a dictionary with the folowing elements:
  'coredata' - an np.array
  'index'    - a list of datetimes
  'colnames' - a list of strings representing column names

"""

import numpy as np
import rpy2.robjects as robjects
from datetime import datetime
import pdb 

##########################################################################
# Convert an R xts object to a python dictionary for plotting 
#
def xts2py(rxts):  
    """
    Pass in the name of an R xts object. 

    """
    pyxts = {}
    pyxts['_Rname']      = rxts   # store it for reference
    pyxts['_indexCLASS'] = robjects.r('attr(' + rxts + ', ".indexCLASS")')[0]
    # 
    pyxts['_rownames']   = np.array(robjects.r('rownames(' + rxts + ')'))
    pyxts['coredata']    = np.array(robjects.r(rxts))
    pyxts['colnames']    = np.array(robjects.r('colnames(' + rxts + ')'))

    indR = np.array(robjects.r('attr(' + rxts + ', "index")'))
    # need a tzinfo here!, try to match R's one
    pyxts['index']       = [datetime.fromtimestamp(x) for x in indR]

    # need to validate your object  

    # pdb.set_trace()    

    return pyxts 

##########################################################################
# Calculate datetime ticks.  Can get t(r)icky.
#
def xticks(x):
    """
    Define heuristics for setting the xticks.  The rules can get 
    complicated.  

    Should we make the xticks dependent on the window size too, so if 
    the user enlarges the window, the xticks adjust?  Maybe not implemented 
    in 1.0.   

    Input is an np.array of datetime objects.  
    """

    # call an R function that does the work ... 
    N      = size(x)
xRange = [min(x), max(x)]
xYears = [elem.year for elem in x]   

    ticks=[]  

    return ticks

def makeXDateBox(ax, boxLabels, boxLocations, boxColor=(0.68, 0.85, 0.90)):
    """
    ax is the current axes.AxesSubplot object
    boxLabels are the strings, locations are the datetime objects where
    you want your labels centered at. 
    """

tboxes = []   # the text boxes
for b in range(size(boxLabels)):
    aux = plt.text(boxLocations[b].toordinal(), 300, boxLabels[b], bbox = dict(boxstyle="square", fc=colBox, ec="none"))
    tboxes.append(aux) 

plt.draw()
   


    return


if __name__ == "__main__":
   robjects.r('require(xts)')
   robjects.r('require(quantmod)')
   robjects.r('rxts = getSymbols("GOOG", auto.assign=FALSE, from="2009-01-01")')

   pyxts = xts.xts2py('rxts')

   pass  
